﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;

namespace StockPoint.Util
{
    public class NetUtil
    {
        public const string NEWLINE = "\r\n";
        public const string MIME_HEADER = "Content-Disposition: form-data; name=\"{0}\"";
        public const string MIME_DATA = MIME_HEADER + NEWLINE + NEWLINE + "{1}";
        public const string MIME_FILE = MIME_HEADER + ";filename=\"{1}\"" + NEWLINE + "Content-Type: application/octet-stream" + NEWLINE + NEWLINE;

        private const int REQ_TIMEOUT = 5000;

        public static HttpWebRequest CreateHttpRequest(string sUrl)
        {
            return CreateHttpRequest(sUrl, HeaderType.None);
        }

        public static HttpWebRequest CreateHttpRequest(string sUrl, HeaderType eType)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sUrl);
            req.Method = "GET";
            req.Timeout = REQ_TIMEOUT;

            if (eType != HeaderType.None)
                SetHeader(eType, ref req);

            return req;
        }

        public static string SendPost(string sUrl, string sData)
        {
            System.Text.Encoding euckr = System.Text.Encoding.GetEncoding(51949);   // euc-kr
            byte[] sendData = euckr.GetBytes(sData);

            HttpWebRequest req = CreateHttpRequest(sUrl, HeaderType.Explorer);
            req.Method = "POST";
            req.Timeout = 5000;
            req.ContentType = "application/x-www-form-urlencoded; charset=euc-kr";
            req.ContentLength = sendData.Length;

            Stream writer = req.GetRequestStream();
            writer.Write(sendData, 0, sendData.Length);
            writer.Close();

            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string sResult = reader.ReadToEnd();
            res.Close();

            return sResult;
        }

        public static string SendMultiPart(string url, StringDictionary sdParam, StringDictionary sdFile)
        {
            //System.Text.Encoding enc = System.Text.Encoding.GetEncoding(51949);   // euc-kr
            System.Text.Encoding enc = System.Text.Encoding.UTF8;

            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            string boundaryContent = Environment.NewLine + "--" + boundary + Environment.NewLine;
            string boundaryContent2 = Environment.NewLine + "--" + boundary + "--" + Environment.NewLine;

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "multipart/form-data; boundary=" + boundary;
            req.KeepAlive = true;
            //req.Accept = @"text/html, application/xhtml+xml, */*";
            //req.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)";
            //req.Referer = "http://mcms.m1004.co.kr/page/Music/RingMusicModifySub.asp?code=176632";
            //req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
            //req.Headers.Add(HttpRequestHeader.AcceptLanguage, "ko-KR");
            //req.Headers.Add(HttpRequestHeader.Pragma, "no-cache");
            //req.Headers.Add(HttpRequestHeader.Cookie, "mcms_id=admin; ASPSESSIONIDSCCQQCAR=NMFPMOJBBNMAAONBGEFLMJKD");
            //req.Credentials = System.Net.CredentialCache.DefaultCredentials;
            //ServicePointManager.Expect100Continue = false;

            Stream memStream = new System.IO.MemoryStream();
            byte[] boundarybytes = enc.GetBytes(boundaryContent);

            // ---------- Param
            foreach (string key in sdParam.Keys)
            {
                if (!string.IsNullOrEmpty(sdParam[key]))
                {
                    memStream.Write(boundarybytes, 0, boundarybytes.Length);

                    byte[] headerbytes = enc.GetBytes(string.Format(MIME_DATA, key, sdParam[key]));
                    memStream.Write(headerbytes, 0, headerbytes.Length);
                }
            }

            // ---------- File
            foreach (string key in sdFile.Keys)
            {
                string sFile = sdFile[key];
                string sFileName = string.IsNullOrEmpty(sFile) ? string.Empty : sFile.Substring(sFile.LastIndexOf("\\") + 1);

                memStream.Write(boundarybytes, 0, boundarybytes.Length);

                byte[] headerbytes = enc.GetBytes(string.Format(MIME_FILE, key, sFileName));
                memStream.Write(headerbytes, 0, headerbytes.Length);

                if (!string.IsNullOrEmpty(sFile))
                {
                    FileStream fileStream = new FileStream(sFile, FileMode.Open, FileAccess.Read);
                    byte[] buffer = new byte[1024];
                    int bytesRead = 0;

                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        memStream.Write(buffer, 0, bytesRead);
                    }
                    fileStream.Close();
                }
            }

            // Last Boundary
            byte[] boundarybytes2 = enc.GetBytes(boundaryContent2);
            memStream.Write(boundarybytes2, 0, boundarybytes2.Length);

            req.ContentLength = memStream.Length;
            Stream requestStream = req.GetRequestStream();

            memStream.Position = 0;
            byte[] tempBuffer = new byte[memStream.Length];
            memStream.Read(tempBuffer, 0, tempBuffer.Length);
            memStream.Close();
            requestStream.Write(tempBuffer, 0, tempBuffer.Length);
            requestStream.Close();

            WebResponse res = req.GetResponse();
            string sResult = GetResponseString(res.GetResponseStream(), enc);
            res.Close();

            req = null;
            res = null;

            return sResult;
        }

        public static string GetPageSource(string sUrl, Encoding enc = null)
        {
            HttpWebRequest req = NetUtil.CreateHttpRequest(sUrl);
            req.Timeout = 10000;

            req.Accept = @"*/*";
            req.Headers.Add(HttpRequestHeader.AcceptCharset, "EUC-KR,utf-8");
            req.Headers.Add(HttpRequestHeader.AcceptEncoding, "EUC-KR,utf-8");
            req.Headers.Add(HttpRequestHeader.AcceptLanguage, "ko");
            req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; GTB7.1; InfoPath.2; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0E; .NET4.0C)";

            if (enc == null)
                return NetUtil.GetSource(req, Encoding.Default);
            else
                return NetUtil.GetSource(req, enc);
        }

        public static string GetPageSourceMobileEuckr(string sUrl, Encoding enc = null)
        {
            HttpWebRequest req = NetUtil.CreateHttpRequest(sUrl, HeaderType.MGalaxyEuckr);
            req.Timeout = 10000;

            CookieContainer cookieContainer = new CookieContainer();
            req.CookieContainer = cookieContainer;

            if (enc == null)
                return NetUtil.GetSource(req, Encoding.Default);
            else
                return NetUtil.GetSource(req, enc);
        }

        public static string GetPageSourceMobile(string sUrl, Encoding enc = null)
        {
            HttpWebRequest req = NetUtil.CreateHttpRequest(sUrl, HeaderType.MGalaxy);
            req.Timeout = 10000;

            CookieContainer cookieContainer = new CookieContainer();
            req.CookieContainer = cookieContainer;

            if (enc == null)
                return GetSource(req, Encoding.Default);
            else
                return GetSource(req, enc);
        }

        public static string GetSource(HttpWebRequest req, Encoding enc)
        {
            string sResult = string.Empty;

            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            Stream reader = res.GetResponseStream();

            int read = 0;
            Byte[] data = new Byte[10240];
            while ((read = reader.Read(data, 0, data.Length)) > 0)
            {
                sResult += enc.GetString(data, 0, read);
                //sResult += System.Text.Encoding.UTF8.GetString(data, 0, read);
            }

            res.Close();

            return sResult;
        }

        public static string GetResponseString(Stream sr, Encoding enc)
        {
            string sResult = string.Empty;

            int read = 0;
            Byte[] data = new Byte[10240];
            while ((read = sr.Read(data, 0, data.Length)) > 0)
            {
                sResult += enc.GetString(data, 0, read);
            }

            return sResult;
        }

        /// <summary>
        /// Call page by get.
        /// </summary>
        public static string CallPage(string url, Encoding enc = null, Cookie ck = null, string auth = "", string contentType = "text/html")
        {
            try
            {
                if (enc == null)
                    enc = Encoding.Default;

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "GET";
                req.Timeout = 5000;
                req.Accept = @"*/*";
                req.ContentType = contentType + "; charset=" + enc.BodyName;
                req.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)";
                req.KeepAlive = true;

                if (ck != null)
                {
                    CookieContainer cc = new CookieContainer();
                    cc.Add(ck);
                    req.CookieContainer = cc;
                }

                if (!string.IsNullOrEmpty(auth))
                {
                    req.Headers.Add(HttpRequestHeader.Authorization, "basic " + StrUtil.Base64Encode(auth, enc) + Environment.NewLine);
                }

                WebResponse res = req.GetResponse();
                string sResult = NetUtil.GetResponseString(res.GetResponseStream(), enc);
                res.Close();

                return sResult;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }


        /// <summary>
        /// Call page by post.
        /// </summary>
        public static string CallPageByPost(string url, string data, Encoding enc = null, Cookie ck = null, string auth = "", string contentType = "text/html")
        {
            try
            {
                if (enc == null)
                    enc = Encoding.Default;

                byte[] sendData = enc.GetBytes(data);

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                req.Timeout = 15000;
                req.ContentType = contentType + "; charset=" + enc.BodyName;
                req.ContentLength = sendData.Length;
                req.Accept = @"*/*";
                req.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)";
                req.Credentials = CredentialCache.DefaultCredentials;

                if (ck != null)
                {
                    CookieContainer cc = new CookieContainer();
                    cc.Add(ck);
                    req.CookieContainer = cc;
                }

                if (!string.IsNullOrEmpty(auth))
                {
                    req.Headers.Add(HttpRequestHeader.Authorization, "basic " + StrUtil.Base64Encode(auth, enc) + Environment.NewLine);
                }

                Stream writer = req.GetRequestStream();
                writer.Write(sendData, 0, sendData.Length);
                writer.Close();

                WebResponse res = req.GetResponse();
                string sResult = NetUtil.GetResponseString(res.GetResponseStream(), enc);
                res.Close();

                return sResult;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public static CookieCollection GetCookieByPost(string url, string data, Encoding enc = null, string auth = "")
        {
            if (enc == null)
                enc = Encoding.Default;

            byte[] sendData = enc.GetBytes(data);

            CookieContainer cc = new CookieContainer();
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.CookieContainer = cc;
            req.Method = "POST";
            req.Timeout = 5000;
            req.ContentType = "application/x-www-form-urlencoded; charset=" + enc.BodyName;
            req.ContentLength = sendData.Length;
            req.Referer = "http://mecs.uplus.co.kr/web/index/indexView.cms";
            req.Host = "mecs.uplus.co.kr";
            req.Accept = @"*/*";
            req.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)";
            req.KeepAlive = true;
            req.AllowAutoRedirect = false;

            if (!string.IsNullOrEmpty(auth))
            {
                req.Headers.Add(HttpRequestHeader.Authorization, "basic " + StrUtil.Base64Encode(auth, enc) + Environment.NewLine);
            }

            Stream writer = req.GetRequestStream();
            writer.Write(sendData, 0, sendData.Length);
            writer.Close();

            HttpWebResponse res = (HttpWebResponse)req.GetResponse();

            if (res.Cookies.Count > 0)
            {
                return res.Cookies;
            }
            else
            {
                return null;
            }
        }

        public static string GetResUrl(HttpWebRequest req)
        {
            string sResult = string.Empty;
            HttpWebResponse res = null;

            try
            {
                res = (HttpWebResponse)req.GetResponse();
                sResult = res.ResponseUri.AbsoluteUri;
            }
            catch (System.Net.WebException ex)
            {
                sResult = ex.Status.ToString();
            }
            catch
            {
                sResult = string.Empty;
            }
            finally
            {
                if (res != null) res.Close();
            }

            return sResult;
        }

        private static void SetHeader(HeaderType eType, ref HttpWebRequest req)
        {
            switch (eType)
            {
                case HeaderType.Explorer:
                    req.Accept = @"*/*";
                    req.Headers.Add(HttpRequestHeader.AcceptCharset, "EUC-KR,utf-8");
                    req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
                    req.Headers.Add(HttpRequestHeader.AcceptLanguage, "ko");
                    req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; GTB7.1; InfoPath.2; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0E; .NET4.0C)";
                    break;

                case HeaderType.Chrome:
                    req.Accept = @"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                    req.Headers.Add(HttpRequestHeader.AcceptCharset, "windows-949,utf-8;q=0.7,*;q=0.3");
                    req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");
                    req.Headers.Add(HttpRequestHeader.AcceptLanguage, "ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4");
                    req.UserAgent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.112 Safari/534.30";
                    break;

                case HeaderType.Firefox:
                    req.Accept = @"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                    req.Headers.Add(HttpRequestHeader.AcceptCharset, "EUC-KR,utf-8;q=0.7,*;q=0.7");
                    req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
                    req.Headers.Add(HttpRequestHeader.AcceptLanguage, "ko-kr,ko;q=0.8,en-us;q=0.5,en;q=0.3");
                    req.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0";
                    break;

                case HeaderType.Safari:
                    req.Accept = @"application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
                    req.Headers.Add(HttpRequestHeader.AcceptCharset, "EUC-KR,utf-8;q=0.7,*;q=0.7");
                    req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
                    req.Headers.Add(HttpRequestHeader.AcceptLanguage, "ko-KR");
                    req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; ko-KR) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1";
                    break;

                case HeaderType.MGalaxy:
                    req.Accept = @"application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
                    req.Headers.Add(HttpRequestHeader.AcceptCharset, "utf-8, iso-8859-1, utf-16, *;q=0.7");
                    req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip");
                    req.Headers.Add(HttpRequestHeader.AcceptLanguage, "ko-KR, en-US");
                    req.UserAgent = "Mozilla/5.0 (Linux; U; Android 2.3.3; ko-kr; SHW-M110S Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1";
                    break;

                case HeaderType.MGalaxyEuckr:
                    req.Accept = @"application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
                    req.Headers.Add(HttpRequestHeader.AcceptCharset, "EUC-KR,utf-8");
                    req.Headers.Add(HttpRequestHeader.AcceptEncoding, "EUC-KR,utf-8");
                    req.Headers.Add(HttpRequestHeader.AcceptLanguage, "ko");
                    req.UserAgent = "Mozilla/5.0 (Linux; U; Android 2.3.3; ko-kr; SHW-M110S Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1";
                    break;

                case HeaderType.MGalaxyTab:
                    req.Accept = @"application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
                    req.Headers.Add(HttpRequestHeader.AcceptCharset, "utf-8, iso-8859-1, utf-16, *;q=0.7");
                    req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip");
                    req.Headers.Add(HttpRequestHeader.AcceptLanguage, "ko-KR, en-US");
                    req.UserAgent = "Mozilla/5.0 (Linux; U; Android 2.2.1; ko-kr; SHW-M180S Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1";
                    break;

            }
        }

        public static Size GetImageSizeByDown2(string sUrl)
        {
            WebClient client = new WebClient();
            Stream stream = null;

            try
            {
                stream = client.OpenRead(sUrl);
                Image imgDown = System.Drawing.Image.FromStream(stream);
                return imgDown.Size;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Flush();
                    stream.Close();
                }
            }

            return new Size(0, 0);
        }

    }
}
